package com.mifengs.mall.ui.write;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mifengs.commonbase.util.FileUtils;
import com.mifengs.mall.Constant;
import com.mifengs.mall.R;
import com.mifengs.commonbase.base.BaseActivity;
import com.mifengs.mall.di.component.DaggerHandWriteCompomemt;
import com.mifengs.mall.di.module.HandWriteModule;
import com.mifengs.mall.util.Tools;
import com.mifengs.mall.widget.MainView;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;


import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * Created by lynn on 2018/1/8.
 */

public class HandWrittenActivity extends BaseActivity<HandWritePresent> implements HandWriteContract.View, EasyPermissions.PermissionCallbacks {
    RelativeLayout mRlQuit;
    @BindView(R.id.linear_clear)
    LinearLayout linearClear;
    @BindView(R.id.linear_upload)
    LinearLayout linearUpload;
    private MainView mainView;
    public static int screenW, screenH;
    private String path;
    public static final int PERMISSION_READ_WRITE_EXTERNAL_STORAGE = 7;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        screenW = getWindowManager().getDefaultDisplay().getWidth();
        screenH = getWindowManager().getDefaultDisplay().getHeight();
        setContentView(R.layout.activity_handwritten);
        ButterKnife.bind(this);
        mainView = (MainView) findViewById(R.id.mainView);
        mainView.setCacheCanvas(screenW, screenH);
    }

    @Override
    public void initInjector() {
        super.initInjector();
        DaggerHandWriteCompomemt.builder()
                .handWriteModule(new HandWriteModule(this))
                .build()
                .inject(this);
    }

    private void savaFile() {
        try {
            File file = new File(Constant.AppPath);
            FileUtils.recursionDeleteFile(file);
            if (!file.exists()) {
                file.mkdirs();
            }
            //根据当前时间生成图片名称
            Calendar c = Calendar.getInstance();
            String name = ""
                    + c.get(Calendar.YEAR) + c.get(Calendar.MONTH) + c.get(Calendar.DAY_OF_MONTH)
                    + c.get(Calendar.HOUR_OF_DAY) + c.get(Calendar.MINUTE) + c.get(Calendar.SECOND)
                    + ".png";

            //合成完整路径，注意 / 分隔符
            path = file.getPath() + "/" + name;
            mainView.saveToFile(path);
//            Toast.makeText(this, "保存成功！\n文件保存在：" + path, Toast.LENGTH_LONG).show();
            List<String> urlList = new ArrayList<>();
            urlList.add(path);
            mPresenter.upLoadImg(urlList);
        } catch (FileNotFoundException e) {
            Toast.makeText(this, "保存失败！\n" + e, Toast.LENGTH_LONG).show();
        }
    }

    @AfterPermissionGranted(PERMISSION_READ_WRITE_EXTERNAL_STORAGE)
    public void readWritePermissions() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(getContext(), perms)) {
            savaFile();
        } else {
            EasyPermissions.requestPermissions(this, "您需要获取读写权限",
                    PERMISSION_READ_WRITE_EXTERNAL_STORAGE, perms);
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        switch (requestCode) {
            case PERMISSION_READ_WRITE_EXTERNAL_STORAGE:
                final Dialog permissionsDialog = new Dialog(this, R.style.dialog);
                permissionsDialog.setContentView(R.layout.dialog);
                TextView tvInfo = (TextView) permissionsDialog.findViewById(R.id.tv_info);
                TextView tvTitle = (TextView) permissionsDialog.findViewById(R.id.tv_title);
                Button btOk = (Button) permissionsDialog.findViewById(R.id.bt_ok);
                tvInfo.setText("需要开启读写权限后才能使用");
                tvTitle.setText("权限申请");
                btOk.setText("去设置");
                permissionsDialog.findViewById(R.id.bt_cancle).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        permissionsDialog.dismiss();
                    }
                });
                permissionsDialog.findViewById(R.id.bt_ok).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = Tools.getAppDetailSettingIntent(getContext());
                        startActivity(intent);
                        permissionsDialog.dismiss();
                    }
                });
                permissionsDialog.show();
                break;
        }
    }

    @Override
    public void toFinish(Object obj) {
        Toast.makeText(this, "手写签名上传成功", Toast.LENGTH_SHORT).show();
        Intent intent = new Intent();
        intent.putExtra("url",obj.toString());
        intent.putExtra("path",path);
        setResult(Constant.HANDWRITE_RESULT,intent);
        finish();
    }

    @OnClick({R.id.linear_clear, R.id.linear_upload,R.id.rl_quit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.linear_clear:
                mainView.clear();
                break;
            case R.id.linear_upload:
                readWritePermissions();
                break;
            case R.id.rl_quit:
                finish();
                break;
        }
    }
}
